package com.hxh.wechat.activity

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import coil.load
import com.billy.android.swipe.SmartSwipe
import com.billy.android.swipe.SmartSwipeWrapper
import com.billy.android.swipe.SwipeConsumer
import com.billy.android.swipe.consumer.DoorConsumer
import com.billy.android.swipe.consumer.SlidingConsumer
import com.billy.android.swipe.consumer.StretchConsumer
import com.billy.android.swipe.listener.SimpleSwipeListener
import com.google.gson.reflect.TypeToken
import com.hxh.wechat.R
import com.hxh.wechat.adpter.StarAdapter
import com.hxh.wechat.api.UserApi
import com.hxh.wechat.model.*
import com.hxh.wechat.util.DBUtil
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import java.io.IOException
import java.util.*
import kotlin.collections.ArrayList


class ActivityChat : Fragment() {
    companion object {
        val starList = ArrayList<Star>()
        private lateinit var recyclerView: RecyclerView
        private lateinit var _view: View

        fun notifyDataSetChanged() {
            Handler(Looper.getMainLooper()).post {
                recyclerView.adapter?.notifyDataSetChanged()
            }
        }

        //查看未签收信息并且进行验签
        private fun queryUnSignMsg(view: View) {
            //查看未签收消息
            UserApi.queryUnSignMsg(DBUtil.getUser(view.context)!!.id)?.enqueue(
                object : Callback {
                    override fun onFailure(call: Call, e: IOException) {
                        println("Failed.")
                        println(e.stackTrace.toString())
                    }

                    @Throws(IOException::class)
                    override fun onResponse(call: Call, response: Response) {
                        val responseData = response.body?.string()
                        //获取所有未签收消息
                        var jsonObject = DBUtil.parseArrayString(responseData!!)
                        var unSignMsgs = DBUtil.getGson().fromJson<ArrayList<UnSignMsg>>(
                            jsonObject,
                            object : TypeToken<ArrayList<UnSignMsg>>() {}.type
                        )

                        for (signMsg in unSignMsgs) {
                            var contactFriend =
                                getUserById(view.context, signMsg.sendUserId) ?: continue
                            //同步聊天记录
                            saveUserChatHistory(
                                chatHistory = ChatHistory(
                                    signMsg.id,
                                    signMsg.acceptUserId,
                                    signMsg.sendUserId,
                                    signMsg.msg,
                                    false,
                                    signMsg.type,
                                    false,
                                    signMsg.createTime,
                                ), view.context
                            );
                            //保持快照设置未读
                            saveUserChatSnapshot(
                                chatSnapshot = ChatSnapshot(
                                    signMsg.acceptUserId,
                                    signMsg.sendUserId,
                                    contactFriend!!.friendFaceImage,
                                    contactFriend.friendNickname,
                                    signMsg.createTime,
                                    signMsg.msg,
                                    false,
                                    signMsg.type
                                ), view.context
                            );
                            //全部签收
                            UserApi.signMessage(signMsg.id)?.enqueue(
                                object : Callback {
                                    override fun onFailure(call: Call, e: IOException) {
                                        println("签收信息${signMsg.id}=====>失败.")
                                        println(e.stackTrace.toString())
                                    }

                                    @Throws(IOException::class)
                                    override fun onResponse(call: Call, response: Response) {
                                        println("签收信息${signMsg.id}=====>成功.")
                                    }
                                })
                        }
                        notifyDataSetChanged()

                    }
                })

        }


        fun initStar() {
            starList.clear()
            queryUnSignMsg(_view);

            starList.add(Star("天气预报","https://img2.baidu.com/it/u=908522252,612545307&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500","天气预报","实时天气预报", Date(),0,3))

            var chatSnapshotArrayList: ArrayList<ChatSnapshot> =
                getUserChatSnapshot(context = _view.context)!!
            if (chatSnapshotArrayList.size == 0) {
                //没有数据
                _view.findViewById<TextView>(R.id.chatTitleSnapshot).text = "暂无数据"
            } else {
                for (chatSnapshot: ChatSnapshot in chatSnapshotArrayList) {
                    //查看历史数据
                    var historyData: ArrayList<ChatHistory> =
                        getUserChatHistoryData(_view.context, chatSnapshot.friendId)!!
                    var readSize = 0;
                    for (chatHistory in historyData) {
                        if (!chatHistory.isRead) {
                            readSize++;
                        }
                    }
                    starList.add(
                        Star(
                            chatSnapshot.friendId,
                            chatSnapshot.friendImg,
                            chatSnapshot.friendNickName,
                            chatSnapshot.msg,
                            chatSnapshot.Date,
                            readSize,
                            chatSnapshot.type
                        )
                    )
                }
                notifyDataSetChanged()
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _view = inflater.inflate(R.layout.activity_chat, container, false)
        recyclerView = _view.findViewById(R.id.rcyView)
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.adapter = StarAdapter(starList)

        SmartSwipe.wrap(recyclerView).addConsumer<StretchConsumer>(StretchConsumer())
            .enableVertical()
        initStar()

        var imageView = _view?.findViewById<ImageView>(R.id.avatarImage)
        imageView?.load(DBUtil.getUser(_view.context)?.faceImage)
        return _view
    }

}